package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.BehaviorMessageConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class ArticleListener {

    private final ApArticleConfigService apArticleConfigService;

    private final ApArticleService apArticleService;

    @KafkaListener(topics = WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void listenerArticleDownOrUp(String message) {
        if (StringUtils.isNotBlank(message)) {
            Map map = JSON.parseObject(message, Map.class);
            apArticleConfigService.updateByMap(map);
        }
    }

    /**
     * 监听文章点赞数更新 到数据库
     * @param message
     */
    @KafkaListener(topics = BehaviorMessageConstants.APP_ARTICLE_LIKES_TOPIC)
    public void listenerArticleLikesCount(String message){
         if(StringUtils.isNotBlank(message)){
             Map map = JSON.parseObject(message, Map.class);
             apArticleService.updateArticleLikesCountToDb(map);
         }
    }

    /**
     * 监听文章点赞数更新 到Redis
     * @param message
     */
    @KafkaListener(topics = BehaviorMessageConstants.APP_ARTICLE_LIKES_COUNT_TOPIC)
    public void listenerArticleLikesCountToRedis(String message){
        if(StringUtils.isNotBlank(message)){
            Map map = JSON.parseObject(message, Map.class);
            apArticleService.updateArticleLikesCountToRedis(map);
        }
    }

    /**
     * 监听文章阅读数更新 到数据库
     * @param message
     */
    @KafkaListener(topics = BehaviorMessageConstants.APP_ARTICLE_READ_COUNT_TOPIC)
    public void listenerArticleReadCount(String message){
        if(StringUtils.isNotBlank(message)){
            Map map = JSON.parseObject(message, Map.class);
            apArticleService.updateArticleViewsCountToDb(map);
        }
    }
}
